<?php
class Helpers_ProductFilter extends Zend_Controller_Action_Helper_Abstract {

	public $view;
	
	public function productFilter($name) {

		$cacheTime = 3600;
		
		/*
		$cookieFilters = array(
			'ages', 
			ProductService::FILTER_PRICE,
			ProductService::FILTER_BRAND,
			ProductService::FILTER_GENDER
		);
		foreach ($cookieFilters as $filter) {
			if (isset($_COOKIE[$filter])) {
				$this->getRequest()->setParam($filter, $this->getRequest()->getParam($filter, $_COOKIE[$filter]));
			}
		}
		*/
		
		$categoryRow = CategoryService::getInstance()->getCategoryByKey($this->getRequest()->getParam('name', ''));
		
		$groupParams = $this->getRequest()->getParams();
		$groupParams['order'] = '';
		//количество элементов в каждом из фильтров

		//по возрасту
		$cache = new Cache_Slot_Array('ages_'.md5(serialize($groupParams)), $cacheTime);
		//$ageList = $cache->load();
		if (empty($ageList)) {
			$ageList = ProductService::getInstance()->getFilter(ProductService::FILTER_AGE);
			/* @var $ages AgeFilterRow */
			$listTmp = array();
			foreach ($ageList as $ages) {
				$filterCounts = CategoryService::getInstance()->getProductListData($categoryRow, 1, 1, 
					array_merge($groupParams, array('ages' => $ages->getMin().'-'.$ages->getMax()))
				);
				if (isset($filterCounts['products_paginator'])) {
					$paginator = $filterCounts['products_paginator'];
					$ages->setCount($paginator->getTotalItemCount());
				}
				$listTmp[] = $ages;
			}
			$ageList = $listTmp;
			//$cache->save($ageList);
		}
		
		//по цене (@todo похорошему товары необходимо внести в ценовой диапазон жестко)
		$cache = new Cache_Slot_Array('price_'.md5(serialize($groupParams)), $cacheTime);
		//$priceList = $cache->load();
		if (empty($priceList)) {
			$priceList = ProductService::getInstance()->getFilter(ProductService::FILTER_PRICE);
			/* @var $price PriceFilterRow */
			$listTmp = array();
			foreach ($priceList as $price) {
				$filterCounts = CategoryService::getInstance()->getProductListData($categoryRow, 1, 1, 
					array_merge($groupParams, array('price' => $price->getMin().'-'.$price->getMax()))
				);
				if (isset($filterCounts['products_paginator'])) {
					$paginator = $filterCounts['products_paginator'];
					$price->setCount($paginator->getTotalItemCount());
				}
				$listTmp[] = $price;
			}
			$priceList = $listTmp;
			//$cache->save($priceList);
		}
		
		//по бренду
		$cache = new Cache_Slot_Array('brand_'.md5(serialize($groupParams)), $cacheTime);
		$brandList = $cache->load();
		if (empty($brandList)) {
			$brandList = ProductService::getInstance()->getBrandAsFilter();
			$brandList = ProductBrandPeer::getInstance()->normalizeByPreferKey($brandList);
			if ($brandList && count($brandList)) {
				//@todo нормализация с получением ids-ов
				$grP = $groupParams;
				$grP['brand'] = array_keys($brandList);
				$filterCounts = CategoryService::getInstance()->getProductListData(
					$categoryRow, 1, count($grP['brand']), 
					array_merge($grP, array('group_by' => 'brand_id')));
				/* @var $brand ProductBrandRow */
				$countExists = array();
				if (isset($filterCounts['products_matches'])) {
					foreach ($filterCounts['products_matches'] as $attrs) {
						$cnt = $attrs['attrs']['@count'];
						$brandId = $attrs['attrs']['@groupby'];
						$brandList[$brandId]->setCount($cnt);
						$countExists[$brandId] = $brandId;
					}
				}
				//исключаем числа где ненашлись бренды
				$brandList = array_intersect_key($brandList, $countExists);
			}
			//$cache->save($brandList);
		}
		
		
		//по полу
		$cache = new Cache_Slot_Array('gender_'.md5(serialize($groupParams)), $cacheTime);
		$genderList = $cache->load();
		if (empty($genderList)) {
			if (isset($groupParams['gender'])) {
				unset($groupParams['gender']);
			}
			$gender0 = CategoryService::getInstance()->getProductListData
							($categoryRow, 1, 3, array_merge($groupParams, array(ProductService::FILTER_GENDER => 0)));
			$gender1 = CategoryService::getInstance()->getProductListData
							($categoryRow, 1, 3, array_merge($groupParams, array(ProductService::FILTER_GENDER => 1)));
			$gender2 = CategoryService::getInstance()->getProductListData
							($categoryRow, 1, 3, array_merge($groupParams, array(ProductService::FILTER_GENDER => 2)));

			$counts = array(0 => 0, 1 => 0, 2 => 0);

			if ($gender0) $counts['0'] = $gender0['products_totalcount'];
			if ($gender1) $counts['1'] = $gender1['products_totalcount'];
			if ($gender2) $counts['2'] = $gender2['products_totalcount'];

			$genderList = array(
				array('id' => '1', 'label' => 'Мужской', 'count' => $counts['1']),
				array('id' => '2', 'label' => 'Женский', 'count' => $counts['2'])
			);
			$cache->save($genderList);
		}
			
		$this->view->product_filter = array(
			ProductService::FILTER_AGE => array(
				'list' => $ageList,
				'val' => $this->getRequest()->getParam('ages')
			),
			ProductService::FILTER_PRICE => array(
				'list' => $priceList,
				'val' => $this->getRequest()->getParam(ProductService::FILTER_PRICE)
			),
			ProductService::FILTER_GENDER => array(
				'list' =>$genderList,
				'val' => $this->getRequest()->getParam(ProductService::FILTER_GENDER)
			),
			ProductService::FILTER_BRAND => array(
				'list' =>$brandList,
				'val' => $this->getRequest()->getParam(ProductService::FILTER_BRAND)
			)
		);
		/*
		setcookie('ages', $this->getRequest()->getParam('ages'), 0, '/');
		setcookie(ProductService::FILTER_PRICE, $this->getRequest()->getParam(ProductService::FILTER_PRICE), 0, '/');
		setcookie(ProductService::FILTER_BRAND, $this->getRequest()->getParam(ProductService::FILTER_BRAND), 0, '/');
		setcookie(ProductService::FILTER_GENDER, $this->getRequest()->getParam(ProductService::FILTER_GENDER), 0, '/');
		*/
		return $this->view->render($name);
	}
	
	
 	public function setView(Zend_View_Interface $view)
    {
        $this->view = $view;
        return $this;
    }
}